package com.jamal2362.apktool.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Build;

import androidx.appcompat.app.AppCompatActivity;

import com.jamal2362.apktool.CrashActivity;

import java.io.FileOutputStream;
import java.io.IOException;

public class TopExceptionHandler implements Thread.UncaughtExceptionHandler {
    private Thread.UncaughtExceptionHandler defaultUEH;
    private AppCompatActivity app;

    public TopExceptionHandler(AppCompatActivity app) {
        this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
        this.app = app;
    }

    public void uncaughtException(Thread t, Throwable e) {
		int mCodeName = 1;
		try {
			PackageInfo pInfo = app.getPackageManager().getPackageInfo(app.getPackageName(), 0);
			mCodeName = pInfo.versionCode;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
        StackTraceElement[] arr = e.getStackTrace();
        String report = e.toString() + "\n\n";
		report += "---------------------------------\n\n";
        report += "-------- Stack trace -------\n\n";
		report += "---------------------------------\n\n";
        for (int i=0; i < arr.length; i++) {
            report += "    " + arr[i].toString() + "\n";
        }
        report += "\n---------------------------------\n\n";
        report += "----------- Cause -----------\n\n";
		report += "---------------------------------\n\n";
        Throwable cause = e.getCause();
        if (cause != null) {
            report += cause.toString() + "\n\n";
            arr = cause.getStackTrace();
            for (int i=0; i < arr.length; i++) {
                report += "    " + arr[i].toString() + "\n";
            }
        }
        report += "\n---------------------------------\n\n";
		report += "----------- System ----------\n\n";
		report += "---------------------------------\n\n";
		report +=  "BUILD Code: " + mCodeName + "\n";
        report +=  "SDK Code: " + Build.VERSION.SDK_INT + "\n";
		report +=  "HASH Code: " + MUtil.getSign(app) + (MUtil.strt(app) ? 1 : 0)  + "\n\n";
        report += "----------------------------------\n\n";
        try {
            FileOutputStream trace = app.openFileOutput("stack.trace", Context.MODE_PRIVATE);
            trace.write(report.getBytes());
            trace.close();
			Intent j = new Intent(app, CrashActivity.class);
			app.startActivity(j);
        } catch (IOException ioe) {
			ioe.printStackTrace();
        }
        defaultUEH.uncaughtException(t, e);
    }
}

